package com.qifan.alb2b.action.front;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.qifan.alb2b.domain.CompanyInfoDomain;
import com.qifan.alb2b.domain.UserInfoDomain;
import com.qifan.alb2b.exception.BusinessException;
import com.qifan.alb2b.service.CompanyInfoService;
import com.qifan.alb2b.service.UserInfoService;
import com.qifan.alb2b.util.Constants;
import com.qifan.alb2b.util.ID;
import com.qifan.alb2b.util.Stringer;

@Controller
@RequestMapping("/user")
public class RegManageController{
	private UserInfoService userInfoService;
	private CompanyInfoService companyInfoService;

	public void setCompanyInfoService(CompanyInfoService companyInfoService) {
		this.companyInfoService = companyInfoService;
	}

	public void setUserInfoService(UserInfoService userInfoService) {
		this.userInfoService = userInfoService;
	}
	
	
	@RequestMapping("/register.usr")
	@ResponseBody
	public Map<String, Object> reg(UserInfoDomain userInfoDomain,CompanyInfoDomain companyInfoDomain){
		String id = ID.next() + "";
		String id2 = ID.next() + "";
		Map<String, Object> map=new HashMap<String, Object>();
		boolean bool = userInfoService.getUserByUserName(userInfoDomain.getUserName());
		try{
		
		companyInfoDomain.setCompId(id);// 设置唯一ID
		companyInfoDomain.setCreateTime(new Date());
		companyInfoService.add(companyInfoDomain);
	
		if(bool){
			if(userInfoDomain.getUserBirth()==null||"".equals(userInfoDomain.getUserBirth())){
				userInfoDomain.setUserBirth(null);
			}
			userInfoDomain.setUserId(id2);//设置唯一ID
			userInfoDomain.setCompId(id);//设置唯一ID
			userInfoDomain.setUserPwd(Stringer.md5(userInfoDomain.getUserPwd()).substring(0,30));
			userInfoDomain.setStatus(Constants.EXAMINE);
			userInfoDomain.setCreateTime(new Date());//设置创建日期
			userInfoService.add(userInfoDomain);	
		}
		}catch(Exception e){
			companyInfoService.delete(new String[]{id});
			userInfoService.delete(new String[]{id2});
			 throw new BusinessException("注册失败！");
		}
		map.put("success", true);
		return map;
	}
	
	
	
}
